package com.bzkj.web.controller.system;

import com.bzkj.basicinfo.domain.basic.BasicStoArea;
import com.bzkj.basicinfo.service.basic.BasicStoStockService;
import com.bzkj.common.annotation.LogC;
import com.bzkj.common.constant.UserConstants;
import com.bzkj.common.core.controller.BaseController;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.entity.SysDept;
import com.bzkj.common.core.domain.entity.SysRole;
import com.bzkj.common.core.domain.entity.SysUser;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.enums.BusinessType;
import com.bzkj.common.utils.SecurityUtils;
import com.bzkj.common.utils.StringUtils;
import com.bzkj.common.utils.poi.CsvExportUtils;
import com.bzkj.common.utils.poi.ExcelPDFUtil;
import com.bzkj.common.utils.poi.ExcelUtil;
import com.bzkj.system.service.ISysDeptService;
import com.bzkj.system.service.ISysPostService;
import com.bzkj.system.service.ISysRoleService;
import com.bzkj.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private BasicStoStockService stoStockService;

    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @LogC(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public AjaxResult export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
        return AjaxResult.success();
    }

    @LogC(title = "用户管理", businessType = BusinessType.EXPORTPDF)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/exportPdf")
    public AjaxResult exportPdf(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelPDFUtil<SysUser> util = new ExcelPDFUtil<SysUser>(SysUser.class);
        return util.exportPDF(response, list, "用户数据","用户数据",getUsername(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),"全量");
    }

    @LogC(title = "用户管理", businessType = BusinessType.EXPORTCSV)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/exportCsv")
    public AjaxResult exportCsv(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        try {
            CsvExportUtils.exportToWeb(response, "用户数据.csv", list);
            return AjaxResult.success("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.success("导出失败");
        }
    }

    @LogC(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        //查询所有角色
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        //查询所有岗位
        ajax.put("posts", postService.selectPostAll());
        //查询所有仓库
        ajax.put("warehouses",stoStockService.selectAllBasicStoStock("",""));
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));//角色列表
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));//岗位
            //增加仓库选择框
            ajax.put("warehouse",stoStockService.selectWarehouseListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @LogC(title = "用户管理", businessType = BusinessType.INSERT,
            tableNames = "sys_user",pkFieldNames = "user_id",
            content = "'用户名称：'+#user.nickName")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
//        //检验用户是否存在于erp系统中
//        if (!userService.checkErpUserName(user.getNickName())) {
//            return error("新增用户'" + user.getNickName() + "'失败，erp系统中不存在该用户");
//        }
        Pattern r = Pattern.compile(UserConstants.PASSWORD_REGEXP);
        Matcher m = r.matcher(user.getPassword());
        if(!m.matches()){
            return AjaxResult.error("密码格式错误，长度：6位-20位，且至少包含大写字母、小写字母、数字， 特殊字符中的3种");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        List<Map<String, String>> maps = assemblyData(user.getWarehouseIds());
        user.setNccStoMap(maps);
        return toAjax(userService.insertUser(user));
    }
    /**
     * 新增用户仓库信息
     *
     * @param warehouseIds 仓库组
     */
    public List<Map<String, String>> assemblyData(String[] warehouseIds) {
        List<Map<String, String>> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(warehouseIds)) {
            Map<String, String> map = new HashMap<>();
            for (String warehouseId : warehouseIds) {
                BasicStoArea stoStock = stoStockService.queryOneByStoId(String.valueOf(warehouseId));
//                String str = stoStock.getPkStoDoc() + "," + stoStock.getStoCode();
//                map.put(String.valueOf(warehouseId), str);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @LogC(title = "用户管理", businessType = BusinessType.UPDATE,
            tableNames = "sys_user",pkFieldNames = "user_id",
            content = "'用户昵称：'+#user.userName")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        List<Map<String, String>> maps = assemblyData(user.getWarehouseIds());
        user.setNccStoMap(maps);
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @LogC(title = "用户管理", businessType = BusinessType.DELETE,content = "'用户id'+#userIds")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @LogC(title = "用户管理", businessType = BusinessType.RESETPASSWORD,content = "'用户昵称：'+#user.nickName")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        Pattern r = Pattern.compile(UserConstants.PASSWORD_REGEXP);
        Matcher m = r.matcher(user.getPassword());
        if(!m.matches()){
            return AjaxResult.error("密码格式错误，长度：6位-20位，且至少包含大写字母、小写字母、数字， 特殊字符中的3种");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @LogC(title = "用户管理", businessType = BusinessType.UPDATE,
            tableNames = "sys_user",pkFieldNames = "user_id",
            content = "'用户ID：'+#user.userId")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @LogC(title = "用户管理", businessType = BusinessType.GRANT,content = "'用户id：'+#userId")
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    @DeleteMapping("/deleteByUserId")
    public AjaxResult deleteByUserId(Long userId){
        int i = userService.deleteUserById(userId);
        if(i>0){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }

    }
}
